<template>
  <base-breadcrumb :title="title">
    <!-- 质量岗位责任制详情 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading">
        <!-- 基础信息 -->
        <a-card :bordered="false" style="margin-bottom: 50px">
          <title-name title="基础信息"></title-name>
          <custom-form
            :formList="formList"
            :isEmit="false"
            :form="form"
            :editModel="editModel == 0 ? 'V' : ''"
            @selectOrg="selectOrg"
          ></custom-form>
          <title-name :title="editModel == 0 ? '责任书信息' : '责任书分发清单'"></title-name>
          <a-table :loading="listLoading" :dataSource="form.employees" :columns="columns" :pagination="false">
            <!-- 责任书标题 -->
            <template slot="bookName" slot-scope="text, record">
              <div v-if="editModel == 0">{{ text }}</div>
              <a-select v-else v-model="record.bookId" placeholder="请输入责任书标题">
                <a-icon v-if="fetching" slot="suffixIcon" style="color: #096dd9" type="loading" />
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="item in dutyBook" :value="item.id" :key="item.id">
                  <a-tooltip>
                    <template slot="title">
                      {{ item.name }}
                    </template>
                    {{ item.name }}
                  </a-tooltip>
                </a-select-option>
              </a-select>
            </template>
            <!-- 操作栏 -->
            <template slot="actions" slot-scope="text, record, index">
              <a class="del_btn" @click="handleDelete(index)">删除</a>
            </template>
          </a-table>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="tool-btns--fixed btn_box page-btn-right-top">
        <a-button :loading="loading" v-if="editModel != 0" type="primary" class="button_right" @click="handleSubmit"
          >提交</a-button
        >
        <a-button type="primary" @click="$multiTab.close()">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { duty, queryEmployee, postDutyBook } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {},
  data() {
    return {
      loading: false, // 详情加载loading
      listLoading: false, // 列表加载loading
      fetch: false, // 责任书列表加载loading
      editModel: 0, // 0 查看；1 编辑；2 新增
      form: {
        creatorName: void 0,
        createTime: void 0,
        employees: [],
        viewName: ''
      },
      rules: {
        branchComId: [{ required: true, message: '请选择分公司名称', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }]
      }, // 表单校验规则
      titles: ['查看质量岗位责任制', '编辑质量岗位责任制', '新增质量岗位责任制'], // 标题
      dutyBook: [] // 责任书列表
    }
  },
  created(){
    this.form.projectId =  this.$route.query.projectId
  },
  mounted() {
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      duty
        .detailInfo({ id: this.id })
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            this.form = res.data
            this.form.viewName = this.form.branchComName + '/' + this.form.projectName
          }
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.form.creatorName = this.$userInfo()?.name // 默认填报人
      this.form.createTime = this.$dateFormat(new Date(), 'D') // 默认填报时间
    }
  },
  computed: {
    columns() {
      return [
        {
          title: '序号',
          width: 80,
          dataIndex: 'index',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '员工名称',
          ellipsis: true,
          dataIndex: 'employeeName'
        },
        {
          title: '岗位',
          ellipsis: true,
          dataIndex: 'postName'
        },
        {
          title: '责任书名称',
          dataIndex: 'bookName',
          scopedSlots: { customRender: 'bookName' }
        },
        {
          title: '甲方',
          ellipsis: true,
          dataIndex: 'partyA'
        },
        {
          title: '乙方',
          ellipsis: true,
          dataIndex: 'partyB'
        },
        this.editModel != 0 && {
          title: '操作',
          dataIndex: 'actions',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'actions' }
        }
      ]
    },
    // 表单配置项
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId', 
          disabled: true,
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          isNoBorder: this.editModel == 0,
          viewName: "viewName",
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '分公司名称',
        //   viewName: 'branchComName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   },
        //   change: (e) => {
        //     e && this.getDutyBook()
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '项目名称',
        //   viewName: 'projectName',
        //   attrs: {
        //     keyValue: 'branchComId',
        //     autoSelected: this.editModel == 2,
        //     isClear: this.editModel == 2,
        //     form: this.form,
        //     isMaintenance:true,
        //   },
        //
        //   change: (e) => {
        //     if (!e) {
        //       return
        //     }
        //     // 请求质量责任书列表
        //     this.listLoading = true
        //     queryEmployee
        //       .getList({ projectId: e })
        //       .then((res) => {
        //         this.listLoading = false
        //         if (res.code === '0') {
        //           this.form.employees = res.data || []
        //         }
        //       })
        //       .catch(() => {
        //         this.listLoading = false
        //       })
        //   }
        // },
        {
          keyName: 'creatorName',
          type: 'a-input',
          disabled: true,
          label: '创建人'
        },
        {
          keyName: 'createTime',
          type: 'a-input',
          disabled: true,
          label: '创建时间'
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
      this.getDutyBook()
          // 请求质量责任书列表
          this.listLoading = true
          queryEmployee
            .getList({ projectId: this.form.projectId })
            .then((res) => {
              this.listLoading = false
              if (res.code === '0') {
                this.form.employees = res.data || []
              }
            })
            .catch(() => {
              this.listLoading = false
            })
    },
    /**
     * 删除行详情
     * @param {Number} index -当前行索引值
     */
    handleDelete(index) {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除？',
        onOk: () => {
          this.form.employees.splice(index, 1)
        }
      })
    },
    /**
     * 获取责任书列表
     */
    getDutyBook() {
      this.fetching = true
      postDutyBook
        .getList({ needCount: false, branchComId: this.form.branchComId, isDisable: false })
        .then((res) => {
          this.fetching = false
          if (res.code === 200) {
            this.dutyBook = res.data
          }
        })
        .catch(() => {
          this.fetching = false
        })
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 校验责任书
          if (that.form.employees?.length) {
            for (let index in that.form.employees) {
              let item = that.form.employees[index]
              // 校验责任书标题
              if (!item.bookId) {
                this.$message.warning(`第${Number(index) + 1}行责任书名称不能为空！`)
                return
              }
            }
          } else {
            this.$message.warning('下发质量责任书列表不能为空！')
            return
          }
          that.$confirm({
            title: '温馨提示',
            content: '确定提交，提交后不可撤回？',
            onOk: () => {
              let form = that.$clone(that.form)
              return duty.create(form).then((res) => {
                if (res.code === 200 || res.data.code === 200) {
                  that.$message.success('提交成功！')
                  that.$multiTab.close()
                }
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-calendar-picker {
  width: 100% !important;
}
</style>
